﻿using Microsoft.Win32;
using System;
using System.Collections;
using System.Configuration.Install;
using System.ServiceProcess;

namespace FCRE.helper
{
    public static class WinServiceHelper
    {
        #region 已封装Window服务
        public static string ServerName = "";// ConfigurationManager.AppSettings["WinServiceName"].ToString();
        private static string ExecuteName = "";// ConfigurationManager.AppSettings["ExecuteName"].ToString();
        public static string serviceFileName = "";

        /// <summary>
        /// 启动服务
        /// </summary>
        /// <param name="SName">系统服务名</param>
        /// <param name="SFName">服务对应的应用程序</param>
        /// <returns></returns>
        public static bool StartMySvc(string SName,string SFName)
        {
            ServerName = SName;
            serviceFileName = SFName;
            if (!IsServiceExisted())
            {
                bool isCreated = InstallService();
                if (!isCreated) return false;
            }
            if(IsServiceStart())  return true;
            else
            {
                if (StartService()) return true;
                else return false;
            }
        }
        public static bool StopMySvc(string SName, string SFName)
        {
            ServerName = SName;
            serviceFileName = SFName;
            if (!IsServiceExisted())
            {
                return true;
            }
            if (IsServiceStart())
            {
                if (!StopService())return false;
            }
            if (UninstallService()) return true;
            else return false;

        }
        /// <summary>  
        /// 安装服务  
        /// </summary>  
        /// <param name="NameService">Windows服务显示名称</param>  
        /// <returns>存在返回 true,否则返回 false;</returns>  
        public static bool InstallService()
        {
            bool flag = false;
            if (!IsServiceExisted())
            {
                try
                {
                    //string location = System.Reflection.Assembly.GetExecutingAssembly().Location;
                    //string serviceFileName = location.Substring(0, location.LastIndexOf('\\') + 1) + ExecuteName + ".exe";
                    LogHelper.WriteLog(typeof(WinServiceHelper), "installService...：" + serviceFileName);
                    InstallMyService( serviceFileName);
                    flag = true;
                }
                catch (Exception ex)
                {
                    flag = false;
                    LogHelper.WriteLog(typeof(WinServiceHelper), "InstallService执行错误：" + ex.Message);

                }

            }
            else
            {
                flag = true;
                LogHelper.WriteLog(typeof(WinServiceHelper), "InstallService执行配置服务名称已存在");

            }
            return flag;
        }

        /// <summary>  
        /// 卸载服务  
        /// </summary>  
        /// <param name="NameService">Windows服务显示名称</param>  
        /// <returns>存在返回 true,否则返回 false;</returns>  
        public static bool UninstallService()
        {
            bool flag = false;
            if (IsServiceExisted())
            {
                try
                {
                    //string location = System.Reflection.Assembly.GetExecutingAssembly().Location;
                    //string serviceFileName = location.Substring(0, location.LastIndexOf('\\') + 1) + ExecuteName + ".exe";

                    UnInstallMyService(serviceFileName);
                    flag = true;
                }
                catch (Exception ex)
                {
                    flag = false;
                    LogHelper.WriteLog(typeof(WinServiceHelper), "UninstallService执行错误：" + ex.Message);
                }
            }
            else
            {
                flag = true;
                LogHelper.WriteLog(typeof(WinServiceHelper), "UninstallService执行配置服务名称不存在");
            }
            return flag;
        }


        /// <summary>  
        /// 检查Windows服务是否存在  
        /// </summary>  
        /// <param name="NameService">Windows服务显示名称</param>  
        /// <returns>存在返回 true,否则返回 false;</returns>  
        public static bool IsServiceExisted()
        {
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController s in services)
            {
                if (s.ServiceName.ToLower() == ServerName.ToLower())
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>  
        /// 安装Windows服务  ,，必须是.net制作的程序，才能由安装成为系统服务
        /// </summary>  
        /// <param name="stateSaver">集合</param>  
        /// <param name="filepath">Windows服务程序文件路径</param>  
        private static void InstallMyService( string filePath)
        {
            AssemblyInstaller AssemblyInstaller1 = new AssemblyInstaller();
            AssemblyInstaller1.UseNewContext = true;
            AssemblyInstaller1.Path = filePath;
            IDictionary stateSaver = new Hashtable();
            AssemblyInstaller1.Install(stateSaver);
            AssemblyInstaller1.Commit(stateSaver);
            AssemblyInstaller1.Dispose();
        }

        /// <summary>
        /// 卸载Windows服务  
        /// </summary>
        /// <param name="filePath">Windows服务程序文件路径</param>
        private static void UnInstallMyService(string filePath)
        {
            AssemblyInstaller AssemblyInstaller1 = new AssemblyInstaller();
            AssemblyInstaller1.UseNewContext = true;
            AssemblyInstaller1.Path = filePath;
            AssemblyInstaller1.Uninstall(null);
            AssemblyInstaller1.Dispose();
        }

        /// <summary>
        /// 判断某个Windows服务是否启动  
        /// </summary>
        /// <param name="serviceName">Windows服务显示名称</param>
        /// <returns>bool</returns>
        public static bool IsServiceStart()
        {
            bool bStartStatus = false;
            ServiceController psc = new ServiceController(ServerName);
            try
            {
                if (!psc.Status.Equals(ServiceControllerStatus.Stopped))
                {
                    bStartStatus = true;
                }

                return bStartStatus;
            }
            catch (Exception ex)
            {
                //throw new Exception(ex.Message);
                LogHelper.WriteLog("启动服务" + ServerName + "失败：" + ex.Message);
                return false;
            }

        }

        /// <summary>    
        /// 修改服务的启动项 2为自动,3为手动    
        /// </summary>    
        /// <param name="startType">2为自动,3为手动</param>    
        /// <param name="serviceName">Windows服务显示名称</param>    
        /// <returns>bool</returns>    
        public static bool ChangeServiceStartType(int startType, string serviceName)
        {
            try
            {
                RegistryKey regist = Registry.LocalMachine;
                RegistryKey sysReg = regist.OpenSubKey("SYSTEM");
                RegistryKey currentControlSet = sysReg.OpenSubKey("CurrentControlSet");
                RegistryKey services = currentControlSet.OpenSubKey("Services");
                RegistryKey servicesName = services.OpenSubKey(serviceName, true);
                servicesName.SetValue("Start", startType);
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;


        }

        /// <summary>
        /// 启动服务
        /// </summary>
        /// <param name="serviceName">Windows服务显示名称</param>
        /// <returns>bool</returns>
        public static bool StartService()
        {
            bool flag = true;
            try
            {
                if (IsServiceExisted())
                {
                    ServiceController service = new ServiceController(ServerName);
                    if (service.Status != ServiceControllerStatus.Running && service.Status != ServiceControllerStatus.StartPending)
                    {
                        service.Start();
                        int i;
                        for ( i = 0; i < 60; i++)
                        {
                            service.Refresh();
                            System.Threading.Thread.Sleep(1000);
                            if (service.Status == ServiceControllerStatus.Running)
                            {
                                break;
                            }
                        }
                        if (i == 60)
                        {
                            flag = false;
                        }

                    }
                }
                else
                {
                    
                    flag = false;
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(typeof(WinServiceHelper), "StartService执行错误：" + ex.Message);
            }
            return flag;
        }

        /// <summary>
        /// 停止服务
        /// </summary>
        /// <param name="serviceName">Windows服务显示名称</param>
        /// <returns>bool</returns>
        public static bool StopService()
        {
            bool flag = true;
            try
            {
                if (IsServiceExisted())
                {
                    ServiceController service = new ServiceController(ServerName);
                    if (service.Status == ServiceControllerStatus.Running)
                    {
                        service.Stop();
                        int i;
                        for (i = 0; i < 60; i++)
                        {
                            service.Refresh();
                            System.Threading.Thread.Sleep(1000);
                            if (service.Status == ServiceControllerStatus.Stopped)
                            {
                                break;
                            }
                        }
                        if (i == 60)
                        {
                            flag = false;
                        }
                    }
                }
                else
                {
                    flag = false;
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(typeof(WinServiceHelper), "StopService执行错误：" + ex.Message);
            }
            return flag;
        }
        #endregion
    }
}
